<template>
  <div class="stock-management">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>总库存量</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ statistics.totalStock }}</div>
            <div class="trend">
              较上月
              <span :class="statistics.stockTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(statistics.stockTrend) }}%
                <el-icon>
                  <component :is="statistics.stockTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>库存预警</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount warning">{{ statistics.lowStockCount }}</div>
            <div class="percentage">
              占比 {{ statistics.lowStockPercentage }}%
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>待盘点</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ statistics.pendingCheckCount }}</div>
            <div class="percentage">
              占比 {{ statistics.pendingCheckPercentage }}%
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>待调拨</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ statistics.pendingTransferCount }}</div>
            <div class="percentage">
              占比 {{ statistics.pendingTransferPercentage }}%
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleStartCheck">开始盘点</el-button>
      <el-button type="success" @click="handleStartTransfer">库存调拨</el-button>
      <el-button type="warning" @click="handleExportStock">导出库存</el-button>
      <el-button type="info" @click="handleExportRecord">导出记录</el-button>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="商品分类">
          <el-cascader
            v-model="searchForm.categoryId"
            :options="categoryOptions"
            :props="{ checkStrictly: true }"
            clearable
            placeholder="请选择分类"
          />
        </el-form-item>
        <el-form-item label="库存状态">
          <el-select v-model="searchForm.stockStatus" placeholder="请选择" clearable>
            <el-option label="全部" value="" />
            <el-option label="充足" value="sufficient" />
            <el-option label="预警" value="warning" />
            <el-option label="缺货" value="out_of_stock" />
          </el-select>
        </el-form-item>
        <el-form-item label="变动类型">
          <el-select v-model="searchForm.changeType" placeholder="请选择" clearable>
            <el-option label="全部" value="" />
            <el-option label="入库" value="in" />
            <el-option label="出库" value="out" />
            <el-option label="盘点" value="check" />
            <el-option label="调拨" value="transfer" />
          </el-select>
        </el-form-item>
        <el-form-item label="变动时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 库存列表 -->
    <el-card class="stock-card">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="库存列表" name="list">
          <el-table
            v-loading="loading"
            :data="stockList"
            border
            style="width: 100%"
          >
            <el-table-column type="expand">
              <template #default="{ row }">
                <el-table :data="row.specStocks" border>
                  <el-table-column label="规格" prop="specName" />
                  <el-table-column label="库存" prop="stock">
                    <template #default="{ row: specRow }">
                      <span :class="{ 'warning': specRow.stock <= specRow.stockWarning }">
                        {{ specRow.stock }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column label="预警值" prop="stockWarning" />
                  <el-table-column label="操作" width="200">
                    <template #default="{ row: specRow }">
                      <el-button type="primary" link @click="handleAdjustStock(row, specRow)">
                        调整库存
                      </el-button>
                      <el-button type="success" link @click="handleTransferStock(row, specRow)">
                        调拨
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-table-column>
            <el-table-column label="商品信息" min-width="300">
              <template #default="{ row }">
                <div class="product-info">
                  <el-image 
                    :src="row.image" 
                    :preview-src-list="[row.image]"
                    fit="cover"
                    class="product-image"
                  />
                  <div class="product-detail">
                    <div class="product-name">{{ row.name }}</div>
                    <div class="product-code">编码：{{ row.code }}</div>
                    <div class="product-category">{{ row.categoryName }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="totalStock" label="总库存" width="100" />
            <el-table-column prop="stockStatus" label="库存状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStockStatusType(row.stockStatus)">
                  {{ getStockStatusText(row.stockStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="lastCheckTime" label="最后盘点" width="180" />
            <el-table-column prop="lastTransferTime" label="最后调拨" width="180" />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" link @click="handleViewRecord(row)">
                  变动记录
                </el-button>
                <el-button type="success" link @click="handleStartCheck([row])">
                  盘点
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="变动记录" name="record">
          <el-table
            v-loading="recordLoading"
            :data="recordList"
            border
            style="width: 100%"
          >
            <el-table-column label="商品信息" min-width="300">
              <template #default="{ row }">
                <div class="product-info">
                  <el-image 
                    :src="row.productImage" 
                    :preview-src-list="[row.productImage]"
                    fit="cover"
                    class="product-image"
                  />
                  <div class="product-detail">
                    <div class="product-name">{{ row.productName }}</div>
                    <div class="product-code">编码：{{ row.productCode }}</div>
                    <div class="product-spec">{{ row.specName }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="changeType" label="变动类型" width="100">
              <template #default="{ row }">
                <el-tag :type="getChangeTypeTag(row.changeType)">
                  {{ getChangeTypeText(row.changeType) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="changeQuantity" label="变动数量" width="100">
              <template #default="{ row }">
                <span :class="{ 'in': row.changeQuantity > 0, 'out': row.changeQuantity < 0 }">
                  {{ row.changeQuantity > 0 ? '+' : '' }}{{ row.changeQuantity }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="beforeStock" label="变动前" width="100" />
            <el-table-column prop="afterStock" label="变动后" width="100" />
            <el-table-column prop="operator" label="操作人" width="120" />
            <el-table-column prop="reason" label="变动原因" min-width="200" show-overflow-tooltip />
            <el-table-column prop="createTime" label="操作时间" width="180" />
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 库存调整对话框 -->
    <el-dialog
      v-model="stockDialogVisible"
      title="调整库存"
      width="500px"
    >
      <el-form
        ref="stockFormRef"
        :model="stockForm"
        :rules="stockFormRules"
        label-width="100px"
      >
        <el-form-item label="商品名称">
          <span>{{ currentProduct?.name }}</span>
        </el-form-item>
        <el-form-item label="规格">
          <span>{{ currentSpec?.specName }}</span>
        </el-form-item>
        <el-form-item label="当前库存">
          <span>{{ currentSpec?.stock }}</span>
        </el-form-item>
        <el-form-item label="调整方式" prop="type">
          <el-radio-group v-model="stockForm.type">
            <el-radio label="increase">增加</el-radio>
            <el-radio label="decrease">减少</el-radio>
            <el-radio label="set">直接设置</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="调整数量" prop="quantity">
          <el-input-number
            v-model="stockForm.quantity"
            :min="0"
            :precision="0"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="调整原因" prop="reason">
          <el-input
            v-model="stockForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入调整原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="stockDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleStockSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 库存盘点对话框 -->
    <el-dialog
      v-model="checkDialogVisible"
      title="库存盘点"
      width="800px"
    >
      <el-form
        ref="checkFormRef"
        :model="checkForm"
        :rules="checkFormRules"
        label-width="100px"
      >
        <el-form-item label="盘点商品">
          <el-table :data="checkForm.items" border style="width: 100%">
            <el-table-column label="商品信息" min-width="300">
              <template #default="{ row }">
                <div class="product-info">
                  <el-image 
                    :src="row.image" 
                    :preview-src-list="[row.image]"
                    fit="cover"
                    class="product-image"
                  />
                  <div class="product-detail">
                    <div class="product-name">{{ row.name }}</div>
                    <div class="product-code">编码：{{ row.code }}</div>
                    <div class="product-spec">{{ row.specName }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="systemStock" label="系统库存" width="100" />
            <el-table-column label="实际库存" width="150">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.actualStock"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                />
              </template>
            </el-table-column>
            <el-table-column label="差异" width="100">
              <template #default="{ row }">
                <span :class="{ 'warning': row.difference !== 0 }">
                  {{ row.difference }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="盘点备注" prop="remark">
          <el-input
            v-model="checkForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入盘点备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="checkDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCheckSubmit">提交盘点</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 库存调拨对话框 -->
    <el-dialog
      v-model="transferDialogVisible"
      title="库存调拨"
      width="800px"
    >
      <el-form
        ref="transferFormRef"
        :model="transferForm"
        :rules="transferFormRules"
        label-width="100px"
      >
        <el-form-item label="调出商品">
          <div class="product-info">
            <el-image 
              :src="currentProduct?.image" 
              :preview-src-list="[currentProduct?.image]"
              fit="cover"
              class="product-image"
            />
            <div class="product-detail">
              <div class="product-name">{{ currentProduct?.name }}</div>
              <div class="product-code">编码：{{ currentProduct?.code }}</div>
              <div class="product-spec">{{ currentSpec?.specName }}</div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="当前库存">
          <span>{{ currentSpec?.stock }}</span>
        </el-form-item>
        <el-form-item label="调拨数量" prop="quantity">
          <el-input-number
            v-model="transferForm.quantity"
            :min="1"
            :max="currentSpec?.stock"
            :precision="0"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="调入仓库" prop="targetWarehouse">
          <el-select v-model="transferForm.targetWarehouse" placeholder="请选择调入仓库">
            <el-option
              v-for="warehouse in warehouseOptions"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="调拨原因" prop="reason">
          <el-input
            v-model="transferForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入调拨原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="transferDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleTransferSubmit">提交调拨</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 变动记录详情对话框 -->
    <el-dialog
      v-model="recordDialogVisible"
      title="变动记录详情"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="商品名称">{{ currentRecord?.productName }}</el-descriptions-item>
        <el-descriptions-item label="商品编码">{{ currentRecord?.productCode }}</el-descriptions-item>
        <el-descriptions-item label="规格">{{ currentRecord?.specName }}</el-descriptions-item>
        <el-descriptions-item label="变动类型">
          <el-tag :type="getChangeTypeTag(currentRecord?.changeType)">
            {{ getChangeTypeText(currentRecord?.changeType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="变动数量">
          <span :class="{ 'in': currentRecord?.changeQuantity > 0, 'out': currentRecord?.changeQuantity < 0 }">
            {{ currentRecord?.changeQuantity > 0 ? '+' : '' }}{{ currentRecord?.changeQuantity }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="变动前">{{ currentRecord?.beforeStock }}</el-descriptions-item>
        <el-descriptions-item label="变动后">{{ currentRecord?.afterStock }}</el-descriptions-item>
        <el-descriptions-item label="操作人">{{ currentRecord?.operator }}</el-descriptions-item>
        <el-descriptions-item label="操作时间">{{ currentRecord?.createTime }}</el-descriptions-item>
        <el-descriptions-item label="变动原因" :span="2">{{ currentRecord?.reason }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import {
  getMerchantStockStatistics,
  getMerchantStockList,
  getMerchantStockRecordList,
  updateMerchantStock,
  createMerchantStockCheck,
  createMerchantStockTransfer,
  getMerchantWarehouseList,
  exportMerchantStock,
  exportMerchantStockRecord
} from '@/api/merchant'

// 统计数据
const statistics = reactive({
  totalStock: 0,
  stockTrend: 0,
  lowStockCount: 0,
  lowStockPercentage: 0,
  pendingCheckCount: 0,
  pendingCheckPercentage: 0,
  pendingTransferCount: 0,
  pendingTransferPercentage: 0
})

// 搜索表单
const searchForm = reactive({
  name: '',
  categoryId: null,
  stockStatus: '',
  changeType: '',
  dateRange: []
})

// 分类选项
const categoryOptions = ref([])

// 仓库选项
const warehouseOptions = ref([])

// 标签页
const activeTab = ref('list')

// 加载状态
const loading = ref(false)
const recordLoading = ref(false)

// 列表数据
const stockList = ref([])
const recordList = ref([])

// 分页
const page = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框相关
const stockDialogVisible = ref(false)
const checkDialogVisible = ref(false)
const transferDialogVisible = ref(false)
const recordDialogVisible = ref(false)

// 当前操作的商品和规格
const currentProduct = ref(null)
const currentSpec = ref(null)
const currentRecord = ref(null)

// 库存调整表单
const stockFormRef = ref(null)
const stockForm = reactive({
  type: 'increase',
  quantity: 0,
  reason: ''
})

// 盘点表单
const checkFormRef = ref(null)
const checkForm = reactive({
  items: [],
  remark: ''
})

// 调拨表单
const transferFormRef = ref(null)
const transferForm = reactive({
  quantity: 1,
  targetWarehouse: '',
  reason: ''
})

// 表单验证规则
const stockFormRules = {
  type: [{ required: true, message: '请选择调整方式', trigger: 'change' }],
  quantity: [{ required: true, message: '请输入调整数量', trigger: 'blur' }],
  reason: [{ required: true, message: '请输入调整原因', trigger: 'blur' }]
}

const checkFormRules = {
  remark: [{ required: true, message: '请输入盘点备注', trigger: 'blur' }]
}

const transferFormRules = {
  quantity: [{ required: true, message: '请输入调拨数量', trigger: 'blur' }],
  targetWarehouse: [{ required: true, message: '请选择调入仓库', trigger: 'change' }],
  reason: [{ required: true, message: '请输入调拨原因', trigger: 'blur' }]
}

// 获取统计数据
const getStatistics = async () => {
  try {
    const { data } = await getMerchantStockStatistics()
    Object.assign(statistics, data)
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 获取库存列表
const getStockList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      page: page.current,
      size: page.size
    }
    const { data } = await getMerchantStockList(params)
    stockList.value = data.list
    page.total = data.total
  } catch (error) {
    console.error('获取库存列表失败:', error)
    ElMessage.error('获取库存列表失败')
  } finally {
    loading.value = false
  }
}

// 获取变动记录
const getRecordList = async () => {
  recordLoading.value = true
  try {
    const params = {
      ...searchForm,
      page: page.current,
      size: page.size
    }
    const { data } = await getMerchantStockRecordList(params)
    recordList.value = data.list
    page.total = data.total
  } catch (error) {
    console.error('获取变动记录失败:', error)
    ElMessage.error('获取变动记录失败')
  } finally {
    recordLoading.value = false
  }
}

// 获取仓库列表
const getWarehouseList = async () => {
  try {
    const { data } = await getMerchantWarehouseList()
    warehouseOptions.value = data
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    ElMessage.error('获取仓库列表失败')
  }
}

// 搜索
const handleSearch = () => {
  page.current = 1
  if (activeTab.value === 'list') {
    getStockList()
  } else {
    getRecordList()
  }
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'categoryId' ? null : key === 'dateRange' ? [] : ''
  })
  handleSearch()
}

// 分页
const handleSizeChange = (val) => {
  page.size = val
  handleSearch()
}

const handleCurrentChange = (val) => {
  page.current = val
  handleSearch()
}

// 获取库存状态类型
const getStockStatusType = (status) => {
  const map = {
    sufficient: 'success',
    warning: 'warning',
    out_of_stock: 'danger'
  }
  return map[status]
}

// 获取库存状态文本
const getStockStatusText = (status) => {
  const map = {
    sufficient: '充足',
    warning: '预警',
    out_of_stock: '缺货'
  }
  return map[status]
}

// 获取变动类型标签
const getChangeTypeTag = (type) => {
  const map = {
    in: 'success',
    out: 'danger',
    check: 'warning',
    transfer: 'info'
  }
  return map[type]
}

// 获取变动类型文本
const getChangeTypeText = (type) => {
  const map = {
    in: '入库',
    out: '出库',
    check: '盘点',
    transfer: '调拨'
  }
  return map[type]
}

// 调整库存
const handleAdjustStock = (product, spec) => {
  currentProduct.value = product
  currentSpec.value = spec
  Object.keys(stockForm).forEach(key => {
    stockForm[key] = key === 'type' ? 'increase' : ''
  })
  stockForm.quantity = 0
  stockDialogVisible.value = true
}

// 提交库存调整
const handleStockSubmit = async () => {
  if (!stockFormRef.value) return
  
  try {
    await stockFormRef.value.validate()
    const { type, quantity, reason } = stockForm
    let finalQuantity = quantity
    
    if (type === 'decrease') {
      finalQuantity = -quantity
    } else if (type === 'set') {
      finalQuantity = quantity - currentSpec.value.stock
    }
    
    await updateMerchantStock(currentProduct.value.id, {
      specId: currentSpec.value.id,
      quantity: finalQuantity,
      reason
    })
    ElMessage.success('库存调整成功')
    stockDialogVisible.value = false
    getStockList()
    getStatistics()
  } catch (error) {
    console.error('调整库存失败:', error)
  }
}

// 开始盘点
const handleStartCheck = (products = null) => {
  if (products) {
    checkForm.items = products.map(product => ({
      id: product.id,
      name: product.name,
      code: product.code,
      image: product.image,
      specName: product.specName,
      systemStock: product.stock,
      actualStock: product.stock,
      difference: 0
    }))
  } else {
    // 获取所有需要盘点的商品
    checkForm.items = stockList.value.map(product => ({
      id: product.id,
      name: product.name,
      code: product.code,
      image: product.image,
      specName: product.specName,
      systemStock: product.stock,
      actualStock: product.stock,
      difference: 0
    }))
  }
  checkForm.remark = ''
  checkDialogVisible.value = true
}

// 提交盘点
const handleCheckSubmit = async () => {
  if (!checkFormRef.value) return
  
  try {
    await checkFormRef.value.validate()
    const items = checkForm.items.map(item => ({
      productId: item.id,
      specId: item.specId,
      systemStock: item.systemStock,
      actualStock: item.actualStock,
      difference: item.actualStock - item.systemStock
    }))
    
    await createMerchantStockCheck({
      items,
      remark: checkForm.remark
    })
    ElMessage.success('盘点提交成功')
    checkDialogVisible.value = false
    getStockList()
    getStatistics()
  } catch (error) {
    console.error('提交盘点失败:', error)
  }
}

// 调拨库存
const handleTransferStock = (product, spec) => {
  currentProduct.value = product
  currentSpec.value = spec
  transferForm.quantity = 1
  transferForm.targetWarehouse = ''
  transferForm.reason = ''
  transferDialogVisible.value = true
}

// 提交调拨
const handleTransferSubmit = async () => {
  if (!transferFormRef.value) return
  
  try {
    await transferFormRef.value.validate()
    await createMerchantStockTransfer({
      productId: currentProduct.value.id,
      specId: currentSpec.value.id,
      quantity: transferForm.quantity,
      targetWarehouse: transferForm.targetWarehouse,
      reason: transferForm.reason
    })
    ElMessage.success('调拨申请提交成功')
    transferDialogVisible.value = false
    getStockList()
    getStatistics()
  } catch (error) {
    console.error('提交调拨失败:', error)
  }
}

// 查看变动记录
const handleViewRecord = (product) => {
  currentProduct.value = product
  activeTab.value = 'record'
  searchForm.name = product.name
  getRecordList()
}

// 查看记录详情
const handleViewRecordDetail = (record) => {
  currentRecord.value = record
  recordDialogVisible.value = true
}

// 导出库存
const handleExportStock = async () => {
  try {
    const params = { ...searchForm }
    await exportMerchantStock(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出库存失败:', error)
    ElMessage.error('导出失败')
  }
}

// 导出记录
const handleExportRecord = async () => {
  try {
    const params = { ...searchForm }
    await exportMerchantStockRecord(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出记录失败:', error)
    ElMessage.error('导出失败')
  }
}

// 监听标签页切换
watch(activeTab, (newTab) => {
  if (newTab === 'list') {
    getStockList()
  } else {
    getRecordList()
  }
})

// 监听盘点表单数据变化
watch(() => checkForm.items, (items) => {
  items.forEach(item => {
    item.difference = item.actualStock - item.systemStock
  })
}, { deep: true })

onMounted(() => {
  getStatistics()
  getStockList()
  getWarehouseList()
})
</script>

<style lang="scss" scoped>
.stock-management {
  .statistics-cards {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .card-content {
      text-align: center;

      .amount {
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 10px;

        &.warning {
          color: var(--el-color-warning);
        }
      }

      .trend {
        font-size: 14px;
        color: var(--el-text-color-secondary);

        .up {
          color: var(--el-color-success);
        }

        .down {
          color: var(--el-color-danger);
        }
      }

      .percentage {
        font-size: 14px;
        color: var(--el-text-color-secondary);
      }
    }
  }

  .action-bar {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
  }

  .search-card {
    margin-bottom: 20px;
  }

  .stock-card {
    .product-info {
      display: flex;
      align-items: center;
      gap: 10px;

      .product-image {
        width: 60px;
        height: 60px;
        border-radius: 4px;
      }

      .product-detail {
        .product-name {
          font-weight: bold;
          margin-bottom: 5px;
        }

        .product-code,
        .product-category {
          font-size: 12px;
          color: var(--el-text-color-secondary);
        }
      }
    }

    .warning {
      color: var(--el-color-warning);
    }

    .in {
      color: var(--el-color-success);
    }

    .out {
      color: var(--el-color-danger);
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 